<template>
  <el-card class="box-card">
    <el-button type="primary" @click="showSaveOrUpdateTrademark(false)">
      添加品牌
    </el-button>
    <el-table v-loading="loading" :data="tableData" border style="width: 100%">
      <el-table-column type="index" align="center" label="序号" width="50" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <template v-slot="{ row }">
          <!-- eslint-disable-next-line -->
          <img class="trademark-logo" :src="row.logoUrl" :alt="row.tmName" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            @click="showSaveOrUpdateTrademark(true, row)"
          >
            修改
          </el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            @click="delTrademark(row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[3, 5, 7, 10]"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next, jumper, total, sizes"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      :title="`${isUpdateTrademark ? '更新' : '添加'}品牌`"
      :visible.sync="isVisible"
      width="50%"
    >
      <el-form
        ref="form"
        :model="trademark"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input v-model="trademark.tmName" />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <el-upload
            class="avatar-uploader"
            :action="`${baseURL}/admin/product/fileUpload`"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <!-- eslint-disable-next-line -->
            <img
              v-if="trademark.logoUrl"
              :src="trademark.logoUrl"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  reqGetBaseTrademark,
  reqSaveTrademark,
  reqUpdateTrademark,
  reqDeleteTrademark
} from '@/api/product/trademark'
export default {
  name: 'Trademark',
  data() {
    return {
      tableData: [],
      // 当前页
      currentPage: 1,
      // 每页条数
      pageSize: 5,
      // 总数
      total: 100,
      // loading
      loading: false,
      // dialog控制器:是否显示
      isVisible: false,
      // dialog修改控制器:是否是更新
      isUpdateTrademark: false,
      // 上传的品牌数据,
      trademark: {
        tmName: '',
        logoUrl: ''
      },
      // 表单验证
      rules: {
        tmName: [
          { required: true, message: '请输入品牌名称', trigger: 'blur' }
        ],
        logoUrl: [
          { required: true, message: '请上传品牌logo', trigger: 'blur' }
        ]
      },
      // 请求地址前缀
      baseURL: process.env.VUE_APP_BASE_API
    }
  },
  async mounted() {
    this.getBaseTrademark()
  },
  methods: {
    // 获取品牌列表数据
    async getBaseTrademark() {
      this.loading = true
      const { data } = await reqGetBaseTrademark(
        this.currentPage,
        this.pageSize
      )
      this.tableData = data.records
      this.currentPage = data.current
      this.pageSize = data.size
      this.total = data.total
      this.loading = false
    },
    // 修改每页条数
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.getBaseTrademark()
    },
    // 修改当前页
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getBaseTrademark()
    },
    // 文件上传成功后的回调
    handleAvatarSuccess(res) {
      // 上传成功后,更新页面的数据,才会在页面中显示
      this.trademark.logoUrl = res.data
      // 文件没有使用v-model,不能实时改变校验结果,上传成功后,清除logoUrl的校验
      this.$refs.form.clearValidate(['logoUrl'])
    },
    // 文件上传前的回调
    beforeAvatarUpload(file) {
      // 文件校验
      const imgType = ['image/jpeg', 'image/jpg', 'image/png']
      const isJPG = imgType.includes(file.type)
      const isLt500k = file.size / 1024 < 500

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt500k) {
        this.$message.error('上传头像图片大小不能超过 500kb!')
      }
      return isJPG && isLt500k
    },
    // 提交文件
    submitForm() {
      // 在提交之前,再进行一次表单校验
      this.$refs.form.validate(async vali => {
        if (vali) {
          // 验证通过,发送请求,把数据上传
          const { tmName, logoUrl, id } = this.trademark
          // 判断是新增,还是修改
          if (this.isUpdateTrademark) {
            // 是更新
            await reqUpdateTrademark({ tmName, logoUrl, id })
          } else {
            // 是新增
            await reqSaveTrademark(tmName, logoUrl)
          }

          this.$message.success('品牌添加成功')
          // 在最后一页更新最新的列表数据
          this.getBaseTrademark()
          // 清空dialog
          this.trademark.tmName = ''
          this.trademark.logoUrl = ''
          // 关闭dialog
          this.isVisible = false
        }
      })
    },
    // 修改内容
    showSaveOrUpdateTrademark(
      isUpdateTrademark,
      trademark = {
        tmName: '',
        logoUrl: ''
      }
    ) {
      // dialog可见
      this.isVisible = true
      this.trademark = { ...trademark }
      // dialog是更新状态
      this.isUpdateTrademark = isUpdateTrademark
      // 清空表单校验结果
      this.$refs.form?.clearValidate()
    },
    // 删除内容
    delTrademark(row) {
      const { id } = row
    }
  }
}
</script>

<style lang="scss" scoped>
.trademark-logo {
  width: 80px;
  height: 75px;
}
</style>
